// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.BatchDetails;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.BatchDetailsMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.PurchaseOrderMapper;
import com.fowo.api.mapper.PurchasePlansMapper;
import com.fowo.api.mapper.ReceiptMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.StockInMapper;
import com.fowo.api.mapper.SupplierMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.batch.details.BatchDetailsExcelPo;
import com.fowo.api.model.batch.details.BatchDetailsHideZeroAction;
import com.fowo.api.model.batch.details.BatchDetailsImportPo;
import com.fowo.api.model.batch.details.BatchDetailsItemVo;
import com.fowo.api.model.batch.details.BatchDetailsSearchParamPo;
import com.fowo.api.model.batch.details.BatchDetailsVo;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.purchase.order.PurchaseOrderItemVo;
import com.fowo.api.model.purchase.order.PurchaseOrderSearchParamPo;
import com.fowo.api.model.purchase.plans.PurchasePlansItemVo;
import com.fowo.api.model.purchase.plans.PurchasePlansSearchParamPo;
import com.fowo.api.model.receipt.ReceiptItemVo;
import com.fowo.api.model.receipt.ReceiptSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.stock.in.StockInItemVo;
import com.fowo.api.model.stock.in.StockInSearchParamPo;
import com.fowo.api.model.supplier.SupplierItemVo;
import com.fowo.api.model.supplier.SupplierSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.BatchDetailsService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysArea;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysAreaMapper;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysAreaSearchParamPo;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 批次明细 服务实现类
 * @author 蜂窝蜜造平台 配置人：陈新新，沈友谅
 */
@Service
@Slf4j
@DataObjectType(BatchDetails.class)
@DS("ds24")
public class BatchDetailsServiceImpl
  extends ServiceImpl<BatchDetailsMapper, BatchDetails>
  implements BatchDetailsService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("tradeNameName", "p.`name`");
      put("shopShopName", "si.`shop_name`");
      put("wareHouseName", "w.`name`");
      put("inboundDocumentsCgRealname", "si2.`cg_realname`");
      put("inboundDocumentsOrderSn", "si2.`order_sn`");
      put("countryName", "sa.`name`");
      put("procurementPlanningPpgSn", "pp.`ppg_sn`");
      put("purchaseOrderPurchaseOrderCode", "po.`purchase_order_code`");
      put("goodsReceiptOrderSn", "r.`order_sn`");
      put("supplierSupplierName", "s.`supplier_name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected BatchDetailsService self;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected StockInMapper stockInMapper;

  @Resource
  protected SysAreaMapper sysAreaMapper;

  @Resource
  protected PurchasePlansMapper purchasePlansMapper;

  @Resource
  protected PurchaseOrderMapper purchaseOrderMapper;

  @Resource
  protected ReceiptMapper receiptMapper;

  @Resource
  protected SupplierMapper supplierMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected BatchDetailsHideZeroAction batchDetailsHideZeroAction;

  @Resource
  protected Validator validator;

  /**
   * 创建批次明细
   * @param model 批次明细
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(BatchDetailsVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    BatchDetails entity = new BatchDetails();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getType() == null) {
      entity.setType("QTRK02");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getBatchNum())) {
      entity.setBatchNum(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "BatchDetails.batchNum")
        )
      );
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("批次明细保存失败");
  }

  /**
   * 更新批次明细
   * @param model 批次明细
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(BatchDetailsVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    BatchDetails entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("批次明细不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新批次明细（带空值）
   * @param model 批次明细
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(BatchDetailsVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    BatchDetails entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("批次明细不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(BatchDetails::getLastUpdateTime, model.getLastUpdateTime())
      .set(BatchDetails::getLastUpdateUser, model.getLastUpdateUser())
      .set(BatchDetails::getBatchNum, model.getBatchNum())
      .set(BatchDetails::getType, model.getType())
      .set(BatchDetails::getTradeName, model.getTradeName())
      .set(BatchDetails::getSku, model.getSku())
      .set(BatchDetails::getShop, model.getShop())
      .set(BatchDetails::getMsku, model.getMsku())
      .set(BatchDetails::getFnsku, model.getFnsku())
      .set(BatchDetails::getWareHouse, model.getWareHouse())
      .set(BatchDetails::getSourceBatchNumber, model.getSourceBatchNumber())
      .set(BatchDetails::getOperationTime, model.getOperationTime())
      .set(BatchDetails::getInboundTime, model.getInboundTime())
      .set(
        model.getImg() != null,
        BatchDetails::getImg,
        JSON.toJSONString(model.getImg())
      )
      .setSql(model.getImg() == null, "img = null")
      .set(BatchDetails::getCountry, model.getCountry())
      .set(BatchDetails::getTotal, model.getTotal())
      .set(BatchDetails::getInTransit, model.getInTransit())
      .set(BatchDetails::getAmountInStock, model.getAmountInStock())
      .set(BatchDetails::getAvailableInTransit, model.getAvailableInTransit())
      .set(
        BatchDetails::getDefectiveProductsInTransit,
        model.getDefectiveProductsInTransit()
      )
      .set(BatchDetails::getAmountInspected, model.getAmountInspected())
      .set(BatchDetails::getAvailableAmount, model.getAvailableAmount())
      .set(BatchDetails::getDefectiveQuantity, model.getDefectiveQuantity())
      .set(BatchDetails::getPurchaseUnitPrice, model.getPurchaseUnitPrice())
      .set(BatchDetails::getUnitCosts, model.getUnitCosts())
      .set(BatchDetails::getUnitHeadStroke, model.getUnitHeadStroke())
      .set(BatchDetails::getUnitInventoryCost, model.getUnitInventoryCost())
      .set(BatchDetails::getGoodsValue, model.getGoodsValue())
      .set(BatchDetails::getExpenses, model.getExpenses())
      .set(BatchDetails::getHeadStroke, model.getHeadStroke())
      .set(BatchDetails::getInventoryCost, model.getInventoryCost())
      .set(BatchDetails::getProcurementPlanning, model.getProcurementPlanning())
      .set(BatchDetails::getPurchaseOrder, model.getPurchaseOrder())
      .set(BatchDetails::getGoodsReceipt, model.getGoodsReceipt())
      .set(BatchDetails::getSupplier, model.getSupplier())
      .set(BatchDetails::getAgeInTheLibrary, model.getAgeInTheLibrary())
      .eq(BatchDetails::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(BatchDetailsSearchParamPo search) {
    return false;
  }

  /**
   * 删除批次明细
   * @param id 批次明细的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除批次明细
   * @param ids 批次明细的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<BatchDetailsImportPo> excelToImportRow(
    BatchDetailsImportPo row,
    Integer rowNumber,
    BatchDetailsVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<BatchDetailsImportPo> ir = new ImportRow<BatchDetailsImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<BatchDetailsImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new BatchDetailsVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, BatchDetailsImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM00070")
        );
      BatchDetailsVo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setOperationTime(SheetUtils.tryToDateTime(row.getOperationTime()));
    vo.setInboundTime(SheetUtils.tryToDateTime(row.getInboundTime()));
    vo.setTotal(SheetUtils.tryToInteger(row.getTotal()));
    vo.setInTransit(SheetUtils.tryToInteger(row.getInTransit()));
    vo.setAmountInStock(SheetUtils.tryToInteger(row.getAmountInStock()));
    vo.setAvailableInTransit(
      SheetUtils.tryToInteger(row.getAvailableInTransit())
    );
    vo.setDefectiveProductsInTransit(
      SheetUtils.tryToInteger(row.getDefectiveProductsInTransit())
    );
    vo.setAmountInspected(SheetUtils.tryToInteger(row.getAmountInspected()));
    vo.setAvailableAmount(SheetUtils.tryToInteger(row.getAvailableAmount()));
    vo.setDefectiveQuantity(
      SheetUtils.tryToInteger(row.getDefectiveQuantity())
    );
    vo.setPurchaseUnitPrice(
      SheetUtils.tryToDecimal(row.getPurchaseUnitPrice())
    );
    vo.setUnitCosts(SheetUtils.tryToDecimal(row.getUnitCosts()));
    vo.setUnitHeadStroke(SheetUtils.tryToDecimal(row.getUnitHeadStroke()));
    vo.setUnitInventoryCost(
      SheetUtils.tryToDecimal(row.getUnitInventoryCost())
    );
    vo.setGoodsValue(SheetUtils.tryToDecimal(row.getGoodsValue()));
    vo.setExpenses(SheetUtils.tryToDecimal(row.getExpenses()));
    vo.setHeadStroke(SheetUtils.tryToDecimal(row.getHeadStroke()));
    vo.setInventoryCost(SheetUtils.tryToDecimal(row.getInventoryCost()));
    vo.setAgeInTheLibrary(SheetUtils.tryToInteger(row.getAgeInTheLibrary()));
    // 处理关联字段“品名”
    if (
      !SheetUtils.isBlank(row.getTradeNameName()) &&
      SheetUtils.isBlank(row.getTradeName())
    ) {
      ProductSearchParamPo tradeNameSearchParam = new ProductSearchParamPo();
      tradeNameSearchParam.setLimit(2); // 最大只返回二行记录
      tradeNameSearchParam.setNameEq(SheetUtils.trim(row.getTradeNameName()));
      tradeNameSearchParam.applySqlSegments();
      List<ProductItemVo> tradeNameMatches = productMapper.search(
        tradeNameSearchParam
      );
      if (tradeNameMatches.size() == 0) {
        ir.addError("tradeNameName", "未能在产品管理中找到匹配的数据");
      } else if (tradeNameMatches.size() > 1) {
        ir.addError(
          "tradeNameName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setTradeName(tradeNameMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", tradeNameMatches.get(0).getId())
          .put("fromObjectName", "BatchDetails")
          .put("fromObjectId", vo.getId())
          .put("fromField", "tradeName")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(2);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("sku")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("sku")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("sku")
              .rowFieldName("sku")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("img")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("picUrl")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("img")
              .rowFieldName(null)
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(tradeNameMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopShopName()) &&
      SheetUtils.isBlank(row.getShop())
    ) {
      ShopInfoSearchParamPo shopSearchParam = new ShopInfoSearchParamPo();
      shopSearchParam.setLimit(2); // 最大只返回二行记录
      shopSearchParam.setShopNameEq(SheetUtils.trim(row.getShopShopName()));
      shopSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopMatches = shopInfoMapper.search(shopSearchParam);
      if (shopMatches.size() == 0) {
        ir.addError("shopShopName", "未能在店铺中找到匹配的数据");
      } else if (shopMatches.size() > 1) {
        ir.addError("shopShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setShop(shopMatches.get(0).getId());
      }
    }
    // 处理关联字段“仓库”
    if (
      !SheetUtils.isBlank(row.getWareHouseName()) &&
      SheetUtils.isBlank(row.getWareHouse())
    ) {
      WarehouseSearchParamPo wareHouseSearchParam =
        new WarehouseSearchParamPo();
      wareHouseSearchParam.setLimit(2); // 最大只返回二行记录
      wareHouseSearchParam.setNameEq(SheetUtils.trim(row.getWareHouseName()));
      wareHouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> wareHouseMatches = warehouseMapper.search(
        wareHouseSearchParam
      );
      if (wareHouseMatches.size() == 0) {
        ir.addError("wareHouseName", "未能在仓库即时库存中找到匹配的数据");
      } else if (wareHouseMatches.size() > 1) {
        ir.addError(
          "wareHouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWareHouse(wareHouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“入库单据”
    if (
      !SheetUtils.isBlank(row.getInboundDocumentsCgRealname()) &&
      SheetUtils.isBlank(row.getInboundDocuments())
    ) {
      StockInSearchParamPo inboundDocumentsSearchParam =
        new StockInSearchParamPo();
      inboundDocumentsSearchParam.setLimit(2); // 最大只返回二行记录
      inboundDocumentsSearchParam.setCgRealnameEq(
        SheetUtils.trim(row.getInboundDocumentsCgRealname())
      );
      inboundDocumentsSearchParam.applySqlSegments();
      List<StockInItemVo> inboundDocumentsMatches = stockInMapper.search(
        inboundDocumentsSearchParam
      );
      if (inboundDocumentsMatches.size() == 0) {
        ir.addError(
          "inboundDocumentsCgRealname",
          "未能在入库单中找到匹配的数据"
        );
      } else if (inboundDocumentsMatches.size() > 1) {
        ir.addError(
          "inboundDocumentsCgRealname",
          "关联不唯一，在入库单中找到多个匹配的数据"
        );
      } else {
        vo.setInboundDocuments(inboundDocumentsMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", inboundDocumentsMatches.get(0).getId())
          .put("fromObjectName", "BatchDetails")
          .put("fromObjectId", vo.getId())
          .put("fromField", "inboundDocuments")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(1);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains(
              "inboundTime"
            )
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("createTime")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("inboundTime")
              .rowFieldName("inboundTime")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(inboundDocumentsMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“国家（地区）”
    if (
      !SheetUtils.isBlank(row.getCountryName()) &&
      SheetUtils.isBlank(row.getCountry())
    ) {
      SysAreaSearchParamPo countrySearchParam = new SysAreaSearchParamPo();
      countrySearchParam.setLimit(2); // 最大只返回二行记录
      countrySearchParam.setNameEq(SheetUtils.trim(row.getCountryName()));
      countrySearchParam.applySqlSegments();
      List<SysArea> countryMatches = sysAreaMapper.search(countrySearchParam);
      if (countryMatches.size() == 0) {
        ir.addError("countryName", "未能在地区中找到匹配的数据");
      } else if (countryMatches.size() > 1) {
        ir.addError("countryName", "关联不唯一，在地区中找到多个匹配的数据");
      } else {
        vo.setCountry(countryMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购计划”
    if (
      !SheetUtils.isBlank(row.getProcurementPlanningPpgSn()) &&
      SheetUtils.isBlank(row.getProcurementPlanning())
    ) {
      PurchasePlansSearchParamPo procurementPlanningSearchParam =
        new PurchasePlansSearchParamPo();
      procurementPlanningSearchParam.setLimit(2); // 最大只返回二行记录
      procurementPlanningSearchParam.setPpgSnEq(
        SheetUtils.trim(row.getProcurementPlanningPpgSn())
      );
      procurementPlanningSearchParam.applySqlSegments();
      List<PurchasePlansItemVo> procurementPlanningMatches =
        purchasePlansMapper.search(procurementPlanningSearchParam);
      if (procurementPlanningMatches.size() == 0) {
        ir.addError(
          "procurementPlanningPpgSn",
          "未能在采购计划中找到匹配的数据"
        );
      } else if (procurementPlanningMatches.size() > 1) {
        ir.addError(
          "procurementPlanningPpgSn",
          "关联不唯一，在采购计划中找到多个匹配的数据"
        );
      } else {
        vo.setProcurementPlanning(procurementPlanningMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购单”
    if (
      !SheetUtils.isBlank(row.getPurchaseOrderPurchaseOrderCode()) &&
      SheetUtils.isBlank(row.getPurchaseOrder())
    ) {
      PurchaseOrderSearchParamPo purchaseOrderSearchParam =
        new PurchaseOrderSearchParamPo();
      purchaseOrderSearchParam.setLimit(2); // 最大只返回二行记录
      purchaseOrderSearchParam.setPurchaseOrderCodeEq(
        SheetUtils.trim(row.getPurchaseOrderPurchaseOrderCode())
      );
      purchaseOrderSearchParam.applySqlSegments();
      List<PurchaseOrderItemVo> purchaseOrderMatches =
        purchaseOrderMapper.search(purchaseOrderSearchParam);
      if (purchaseOrderMatches.size() == 0) {
        ir.addError(
          "purchaseOrderPurchaseOrderCode",
          "未能在采购订单中找到匹配的数据"
        );
      } else if (purchaseOrderMatches.size() > 1) {
        ir.addError(
          "purchaseOrderPurchaseOrderCode",
          "关联不唯一，在采购订单中找到多个匹配的数据"
        );
      } else {
        vo.setPurchaseOrder(purchaseOrderMatches.get(0).getId());
      }
    }
    // 处理关联字段“收货单”
    if (
      !SheetUtils.isBlank(row.getGoodsReceiptOrderSn()) &&
      SheetUtils.isBlank(row.getGoodsReceipt())
    ) {
      ReceiptSearchParamPo goodsReceiptSearchParam = new ReceiptSearchParamPo();
      goodsReceiptSearchParam.setLimit(2); // 最大只返回二行记录
      goodsReceiptSearchParam.setOrderSnEq(
        SheetUtils.trim(row.getGoodsReceiptOrderSn())
      );
      goodsReceiptSearchParam.applySqlSegments();
      List<ReceiptItemVo> goodsReceiptMatches = receiptMapper.search(
        goodsReceiptSearchParam
      );
      if (goodsReceiptMatches.size() == 0) {
        ir.addError("goodsReceiptOrderSn", "未能在收货单中找到匹配的数据");
      } else if (goodsReceiptMatches.size() > 1) {
        ir.addError(
          "goodsReceiptOrderSn",
          "关联不唯一，在收货单中找到多个匹配的数据"
        );
      } else {
        vo.setGoodsReceipt(goodsReceiptMatches.get(0).getId());
      }
    }
    // 处理关联字段“供应商”
    if (
      !SheetUtils.isBlank(row.getSupplierSupplierName()) &&
      SheetUtils.isBlank(row.getSupplier())
    ) {
      SupplierSearchParamPo supplierSearchParam = new SupplierSearchParamPo();
      supplierSearchParam.setLimit(2); // 最大只返回二行记录
      supplierSearchParam.setSupplierNameEq(
        SheetUtils.trim(row.getSupplierSupplierName())
      );
      supplierSearchParam.applySqlSegments();
      List<SupplierItemVo> supplierMatches = supplierMapper.search(
        supplierSearchParam
      );
      if (supplierMatches.size() == 0) {
        ir.addError("supplierSupplierName", "未能在供应商中找到匹配的数据");
      } else if (supplierMatches.size() > 1) {
        ir.addError(
          "supplierSupplierName",
          "关联不唯一，在供应商中找到多个匹配的数据"
        );
      } else {
        vo.setSupplier(supplierMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<BatchDetailsImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<BatchDetailsImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            BatchDetailsImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              BatchDetailsImportPo row,
              AnalysisContext cxt
            ) {
              BatchDetailsVo vo = new BatchDetailsVo();
              ImportRow<BatchDetailsImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<BatchDetailsImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<BatchDetailsImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      BatchDetailsVo vo = new BatchDetailsVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"批次号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "batchNum".equals(m.getField())
          )
      ) {
        vo.setBatchNum(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "BatchDetails.batchNum")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    BatchDetailsSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00070")
      );
      exportOptions.addFieldMappingOption(
        "tradeName",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((BatchDetailsItemVo) r).getTradeNameName())
          )
      );
      exportOptions.addFieldMappingOption(
        "shop",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((BatchDetailsItemVo) r).getShopShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "wareHouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((BatchDetailsItemVo) r).getWareHouseName())
          )
      );
      exportOptions.addFieldMappingOption(
        "country",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((BatchDetailsItemVo) r).getCountryName())
          )
      );
      exportOptions.addFieldMappingOption(
        "procurementPlanning",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((BatchDetailsItemVo) r).getProcurementPlanningPpgSn()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "purchaseOrder",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((BatchDetailsItemVo) r).getPurchaseOrderPurchaseOrderCode()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "goodsReceipt",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((BatchDetailsItemVo) r).getGoodsReceiptOrderSn())
          )
      );
      exportOptions.addFieldMappingOption(
        "supplier",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((BatchDetailsItemVo) r).getSupplierSupplierName())
          )
      );
      exportOptions.addStringFields(
        "batchNum",
        "type",
        "tradeNameName",
        "sku",
        "shopShopName",
        "msku",
        "fnsku",
        "wareHouseName",
        "sourceBatchNumber",
        "inboundDocumentsOrderSn",
        "countryName",
        "procurementPlanningPpgSn",
        "purchaseOrderPurchaseOrderCode",
        "goodsReceiptOrderSn",
        "supplierSupplierName"
      );

      String fileName = String.format(
        "批次明细(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> typeItems = sysDictService.getDictItems("SCM00070");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<BatchDetailsExcelPo> items = new ArrayList<BatchDetailsExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<BatchDetailsItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<BatchDetailsItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (BatchDetailsItemVo item : list) {
        BatchDetailsExcelPo excel = new BatchDetailsExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getType() != null) {
          typeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getType()))
            .findFirst()
            .ifPresent(i -> excel.setType(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "批次明细(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(BatchDetailsExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过SKU查询批次明细主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdBySku(String sku) {
    return this.baseMapper.getIdBySku(sku);
  }

  /**
   * 通过SKU查询批次明细多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsBySku(List<String> list) {
    return this.baseMapper.getIdsBySku(list);
  }

  /**
   * 通过批次明细主键查询SKU
   */
  @Override
  public String getSkuById(Long id) {
    return this.baseMapper.getSkuById(id);
  }

  /**
   * 通过批次明细主键查询SKU列表
   */
  @Override
  public List<String> getSkuByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getSkuByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("sku"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 批次明细的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public BatchDetailsVo getVoById(Long id) throws Exception {
    BatchDetailsVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询批次明细
   * @param search 查询条件
   * @return 批次明细分页查询结果
   */
  @Override
  public Page<BatchDetailsItemVo> pageSearch(BatchDetailsSearchParamPo search) {
    Page<BatchDetailsItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(BatchDetailsItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 批次明细快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'BatchDetailsOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<BatchDetailsItemVo>> searchOptions(
    BatchDetailsSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询批次明细
   * @param search 查询条件
   * @return 批次明细列表查询结果
   */
  @Override
  public List<BatchDetailsItemVo> search(BatchDetailsSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询批次明细最后更新时间
   * @param search 查询条件
   * @return 批次明细最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(BatchDetailsSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 隐藏0库存批次
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了隐藏0库存批次操作"
  )
  @Override
  public void hideZero() throws Exception {
    if (batchDetailsHideZeroAction == null) {
      throw new Exception("此操作当前不可用");
    }
    batchDetailsHideZeroAction.run();
  }
}
